'use strict';

import React, { Component } from 'react';
import {
  StyleSheet,
  WebView,
  View,
  Text,
  TouchableOpacity,
  Image,
  ProgressViewIOS,
  Platform
} from 'react-native';
import { SafeAreaView } from 'react-navigation';
import ViewUtil from '../utils/View';
import BaseStyle from '../constants/Style';
import PropTypes from 'prop-types';

/**
 * 使用方法
 * 
 * 
   

 */

export default class WebViewComponent extends Component {
  static defaultProps = {

    checked: true,
  };
  static propTypes = {
    uri: PropTypes.string, // webview加载的uri

  };

  constructor(props) {
    super(props);
    this.state = {
      error: false,
      runNum: false,
      backButtonEnabled: false,
      forwardButtonEnabled: false,
      url: '',
      title: "",
      loading: false,
      progressVal: 0,
    };
  }

  componentWillMount() {
    this.timer = setInterval(() => {
      if (this.state.progressVal == 1) {
        clearInterval(this.timer);

      } else {
        let random = Math.random() * 0.2;
        let progress = this.state.progressVal + random;
        if (progress > 1) {
          progress = 1;
        }
        this.setState({ progressVal: progress });
      }
    }, 200);

  }

  componentDidMount() {


  }
  componentWillUnmount() { }
  onLoadEnd = () => {
    // if (!this.state.runNum) {
    //   let script = `location.reload()`;
    //   this.webView.injectJavaScript(script);

    //   this.setState({ runNum: true })
    // }

    this.setState({
      progressVal: 1
    })
    clearInterval(this.timer);

  }
  onNavigationChange = event => {

    this.setState({
      backButtonEnabled: event.canGoBack,
      forwardButtonEnabled: event.canGoForward,
      url: event.url,
      title: event.title,
      loading: event.loading,
    });

  };
  navOption = () => {
    const { navigation } = this.props;
    if (this.state.backButtonEnabled) {
      this.webView.goBack();  // webview 回退
    } else {
      //回退到RN
      global.nav.goBack();
    }
  }

  render() {
    const { uri, } = this.props;

    return (
      <SafeAreaView style={BaseStyle.flex} forceInset={{ top: 'never' }}>
        {!this.state.error ? (
          <WebView
            source={{ uri: uri }}
            startInLoadingState={true}
            javaScriptEnabled={true}
            mixedContentMode={'always'}
            dataDetectorTypes={'all'}
            ref={webView => (this.webView = webView)}
            scalesPageToFit={true}
            scrollEnabled={true}
            onNavigationStateChange={event => {
              this.onNavigationChange(event);
            }}
            onError={() => this.setState({ error: true })}
            onLoadEnd={this.onLoadEnd}
            style={styles.webviewStyle}
          />
        ) : (
            <View style={styles.view}>
              <Text>页面不见了...</Text>
            </View>
          )}
        <View style={styles.topNav}>
          <Text style={styles.leftNavText}>{this.state.title}</Text>
        </View>
        <TouchableOpacity style={styles.backView} onPress={() => {
          this.navOption()
        }}>
          {
            this.state.backButtonEnabled ?
              <Image style={styles.leftBtn} source={require('../images/leftBack.png')} />
              :
              <Image style={styles.leftBtn} source={require('../images/close.png')} />
          }
        </TouchableOpacity>
        {this.state.progressVal == 1 ?
          null
          :
          Platform.OS === 'ios' ?
            <ProgressViewIOS
              progress={this.state.progressVal}
              style={styles.progStyle}
            />
            :
            null

        }

      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  view: {
    ...BaseStyle.flex,
    ...BaseStyle.alignItemsCenter,
    ...BaseStyle.justifyContentCenter,
  },
  webviewStyle: {
    marginTop: 60,
  },
  topNav: {
    ...BaseStyle.row,
    ...BaseStyle.alignItemsCenter,
    position: "absolute",
    top: 0,
    width: ViewUtil.size.width,
    height: 60,
    backgroundColor: "#fff",
  },
  leftNavText: {
    marginLeft: 30,
    fontSize: 16,
    marginTop: 15
  },
  backView: {
    position: "absolute",
    top: 22,
    left: 5,
    width: 30,
    height: 30,

  },
  leftBtn: {
    width: 15,
    height: 15,
    resizeMode: "contain",
  },
  progStyle: {
    width: ViewUtil.size.width,
    height: 2,
    position: "absolute",
    top: 60,
  },
});
